// mircoApp/activityClock/clockDetails/clockDetails.js
const app = getApp();
import Dialog from '../../../dist/dialog/dialog';
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    active:0,
    id:'',
    query:{
      admin_type:0,
      activity_id:'',
      page:1,
      search:{
        time:[]
      }
    },
    totalPage:0,
    isLoadMore:true,
    awardQuery:{
      activity_id:0,
      page:1
    },
    memberTab:[
      {
        name:'活动详情',
        value:0,
      },
      {
        name:'打卡记录',
        value:1,
      }
    ],
    status:1,
    clockStatus:0,
    timeShow:false, //时间查询
    dateShow:false,
    awardShow:false,
    iPnoneBottomBol: false, //是否是苹果手机
    timeIndex:0,
    timeList:[
      {
        name:'全部',
        value:0,
      },
      {
        name:'最近3天',
        value:1,
      },
      {
        name:'今天',
        value:2,
      },
      {
        name:'昨天',
        value:3,
      },
      {
        name:'上周',
        value:4,
      },
      {
        name:'上月',
        value:5,
      },
      {
        name:'本月',
        value:6,
      }
    ],
    awardList:[],
    recordData:[],
    info:{},
    taskShow:false,
    percentage:'',
    coThemeColor:'',
    pluginId:'',
    //获取当前这周的日期
    weekArr:[],
    //天数
    percentageNum:'',
    timeName:'全部时间',
    clockList:[],
    imgPath:app.globalData.imgPath
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.activityId) {
      this.setData({
        'query.activity_id':Number(options.activityId),
        id:Number(options.id),
        clockStatus:options.clockStatus,
      });
      
    }
    let yz_basic_info = wx.getStorageSync("yz_basic_info");
    if(yz_basic_info) {
      this.setData({
        coThemeColor:this.colorFin(yz_basic_info.theme_color) || this.colorFin('#F15353'),
        pluginId:yz_basic_info.plugin_setting?.check_in_rebate?.plugin_id
      })
    }
    this.getiPnoneBottom();
  },
  initData() {
    this.setData({
      taskShow:false,
      'query.page':1
    })
  },
  colorFin(a) { //处理主题色
    a = a.substring(1);
    a = a.toLowerCase();
    let b = new Array();
    for (let x = 0; x < 3; x++) {
      b[0] = a.substr(x * 2, 2);
      b[3] = "0123456789abcdef";
      b[1] = b[0].substr(0, 1);
      b[2] = b[0].substr(1, 1);
      b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
    }
    return b[20] + "," + b[21] + "," + b[22];
  },
  tabClick(event) {
    let {index} = event.detail;
    this.setData({
      active:index
    });
  },
  percentageInit() {
    let percentNum = 0;
    //连续打卡的情况
    if(this.data.info.is_continuous == 1) {
      percentNum = this.data.partInfo.continuous_day /  this.data.info.count_day;
    } else {
      percentNum = this.data.partInfo.sum_day /  this.data.info.count_day;
    }
    
    let result  = (Math.round(percentNum * 10000) / 10000) * 100;
    this.setData({
      percentageNum:result
    })
  },
  clockOn() {
    if(this.data.clockStatus == 0) {
      wx.navigateTo({
        url: `/packageA/detail_v2/detail_v2?id=${this.data.info.goods_id}`,
      })
    }
  },
  punchTo() {
    wx.navigateTo({
      url: `/mircoApp/activityClock/clockMember/clockMember`,
    })
  },
  calendarTo() {
    wx.navigateTo({
      url: `/mircoApp/activityClock/clockCalendar/clockCalendar?id=${this.data.id}`,
    })
  },
  //跳转售后
  refundOn() {
    wx.navigateTo({
      url: `/packageD/member/myOrder/refund/refund?order_id=${this.data.partInfo.order_id}&type=0&pluginid=${this.data.pluginId}&partId=${this.data.id}&goodsId=${this.data.partInfo.goods_id}`,
    });
  },
  ispartOn() {
    if(this.data.partInfo.is_participate == 1) {
      wx.navigateTo({
        url: `/mircoApp/activityClock/clockAdd/clockAdd?id=${this.data.id}&pluginId=${this.data.pluginId}&goodsId=${this.data.partInfo.goods_id}&orderId=${this.data.partInfo.order_id}`,
      })
    } else {
      this.partCheck();
    }
  },
  closeTask() {
    this.setData({
      taskShow:false
    })
  },
   //获取当前一周的日期
   getWeekDates() {  
      const today = new Date();  
      const dayOfWeek = today.getDay(); // 获取今天是星期几（0-6，0表示周日）
      const todayDate = today.getDate();
      // 计算本周一的日期  
      let startOfWeek = new Date(today);  
      startOfWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));  
    
      // 计算本周日的日期  
      let endOfWeek = new Date(startOfWeek);  
      endOfWeek.setDate(startOfWeek.getDate() + 6);  
    
      // 获取当前一周的每一天日期  
      const weekDates = [];  
      for (let i = 0; i < 7; i++) {  
          const date = new Date(startOfWeek);  
          date.setDate(startOfWeek.getDate() + i); 
          const formattedDate = date.getDate();
          weekDates.push({
            date:formattedDate,
            dataName:formattedDate,
            check_in_type:0
          });  
      }  
      return weekDates;
  },
  recordPost(event){
    let {status,item} = event.currentTarget.dataset;
    let recordQuery = {
      id:item.id
    }
    let message = '';
    if(status == 'hide') {
      item.is_hide==1?message ='取消隐藏打卡记录?':message ='确认隐藏打卡记录?';
      Dialog.confirm({
        title: '提示',
        message:message,
      })
      .then(() => {
        item.is_hide == 0?recordQuery.is_hide=1:recordQuery.is_hide=0;
        recordQuery.check_type = 1;
        this.checkInLogData(recordQuery);
      })
      .catch(() => {
        // on cancel
      });
     
    }
    if(status == 'top') {
      item.is_top==1?message ='取消置顶打卡记录?':message ='确认置顶打卡记录?';
      Dialog.confirm({
        title: '提示',
        message:message,
      })
      .then(() => {
        recordQuery.check_type = 2;
        item.is_top == 0?recordQuery.is_top=1:recordQuery.is_top=0;
        this.checkInLogData(recordQuery);
      })
      .catch(() => {
        // on cancel
      });
    }
    
  },
  checkInLogData(recordQuery) {
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.change-check-in-log");
    app._postNetWork({
      url: urlStr,
      data: recordQuery,
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
         this.setData({
           'query.page':1,
           recordData:[]
         });
         this.recordListData();
        }
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //打卡活动记录参加打卡接口
  partCheck() {
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.participate-in");
    app._postNetWork({
      url: urlStr,
      data: {id:this.data.id},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          app.tips(res.msg);
          this.getMember();
          
        } else {
          Dialog.confirm({
            title: '提示',
            message: '商品订单确认收货后才可以打卡',
          })
          .then(() => {
            // on confirm
            if(data.type == 'no_receive') {
              wx.navigateTo({
                url: '/packageA/member/myOrder_v2/myOrder_v2?status=3',
              });
              // this.$router.push(this.fun.getUrl("orderlist", { status: "3" ,orderType:"shop"}));
            }
          })
          .catch(() => {
            // on cancel
          });
        }
        
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      let value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  getDetail() { //未购买商品的商品详情
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.index.getDetail");
    app._postNetWork({
      url: urlStr,
      data: {id:this.data.query.activity_id},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.setData({
            info:data,
            'awardQuery.activity_id':data.id
          })
          this.awardData();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMember() { //购买商品的商品详情
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.get-detail");
    app._getNetWork({
      url: urlStr,
      data: {id:this.data.id},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.setData({
            info:data.activity,
            partInfo:data,
            'awardQuery.activity_id':data.activity_id
          })
          this.awardData();
          this.percentageInit();
        } else {
          if(data.activity_id) {
            wx.redirectTo({
              url: `/mircoApp/activityClock/clockDetails/clockDetails?id=${data.activity_id}&activityId=${data.activity_id}&clockStatus=0`,
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMemberInfo() { 
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.get-Info");
    app._postNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          if(data.member.is_admin) {
            this.setData({
              'query.admin_type':1
            });
          }
          this.setData({
            memberInfo:data.member,
            isAdmin:data.member?.is_admin
          })
          this.recordListData();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  recordListData() {
    //id查看自己的打卡记录,activity_id查看所有人记录
    // admin_type:1,是管理员状态（可以查看所有的打卡记录），但是只能自己看自己的打卡记录，所以写死状态
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.check-in-log");
    app._postNetWork({
      url: urlStr,
      data:this.data.query,
      success:  (resdata) => {
        let res = resdata.data;
        let data = res.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.setData({
            recordData: data.data,
            total:data.total
          })
        } else {
          this.data.query.page = this.data.query.page - 1;
          this.data.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.query.page >= this.data.totalPage) {
      return;
    } else {
      this.data.query.page = this.data.query.page + 1;
      let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.check-in-log");
      app._postNetWork({
        url: urlStr,
        data: this.data.query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              recordData: this.data.recordData.concat(list.data),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  awardData() {
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.rewards");
    app._postNetWork({
      url: urlStr,
      data:this.data.awardQuery,
      success:  (resdata) => {
        let res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.data.awardTotal = data.last_page;
          if (!this.data.awardTotal) {
            this.data.awardTotal = 0;
          }
          this.setData({
            awardList: data.data,
          })
        } else {
          this.data.awardQuery.page = this.data.awardQuery.page - 1;
          this.data.awardMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
   //获取更多数据
  awardMoreData() {
    this.data.awardMore = false; // 防止多次请求分页数据
    if (this.data.awardQuery.page >= this.data.awardTotal) {
      return;
    } else {
      this.data.awardQuery.page = this.data.awardQuery.page + 1;
      let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.rewards");
      app._postNetWork({
        url: urlStr,
        data: this.data.awardQuery,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data;
          if (res.result == 1) {
            this.data.awardMore = true;
            this.setData({
              awardList: this.data.awardList.concat(list.data),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.data.awardMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  //自己的打卡记录
  clockListData() {
    let query = {
      admin_type:1,
      id:this.data.id,
      page_type:1
    }
    let urlStr = app.getNetAddresss("plugin.check-in-rebate.frontend.participate-in.check-in-log");
    app._postNetWork({
      url: urlStr,
      data:query,
      success:  (resdata) => {
        let res = resdata.data;
        let data = res.data;
        if (res.result == 1) {
          this.data.clockList = data;
          this.data.weekArr = this.getWeekDates() || [];

          //今天的日期
          let now = new Date();
          let toMonth = now.getMonth() + 1;
          let toDay = now.getDate();
          this.data.weekArr.map((item,index) => {
            if(toDay ==  item.date) {
              item.dataName = '今';
            }
            this.data.clockList.map((clockItem,clockIndex) => {
              let time =  new Date(clockItem.created_at);
              let recordMonth = time.getMonth() + 1;
              if(time.getDate() == item.date  && toMonth == recordMonth) {
                item.check_in_type = clockItem.check_in_type
              }
            })
          })
          this.setData({
            weekArr:this.data.weekArr,
            clockList:this.data.clockList
          })
        } else { 
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  awardPop() {
    this.setData({
      awardShow:true
    })
  },
  timeSelect(event) {
    let {item,index} = event.detail;
    this.setData({
      timeIndex:index
    })
  },
  timeConfirm(event) {
    let {result,timeName} = event.detail;
    this.setData({
      timeName:timeName,
      'query.page':1,
      'query.search.time':result,
      recordData:[]
    })
    this.recordListData();
  },
  timePop() {
    this.setData({
      timeShow:true
    })
  },
  
  closeTime() {
    this.setData({
      awardShow:false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initData();
    if(this.data.clockStatus == 1) {
      this.getMember();
      this.clockListData();
    } else {
      this.getDetail();
    }
    this.getMemberInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "活动详情",
      path: `mircoApp/activityClock/clockDetails/clockDetails?id=${this.data.id}&activityId=${this.data.query.activity_id}&clockStatus=${this.data.clockStatus}`,
    };
  },
  onShareTimeline() {
    return {
      title: "活动详情",
      query: `mircoApp/activityClock/clockDetails/clockDetails?id=${this.data.id}&activityId=${this.data.query.activity_id}&clockStatus=${this.data.clockStatus}`,
    };
  }
})